import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainLayout from '../layouts/MainLayout.vue'
import Dashboard from '../views/Dashboard.vue'
import StudyPlan from '../views/StudyPlan.vue'
import StudyRecord from '../views/StudyRecord.vue'
import Subject from '../views/Subject.vue'
import QuestionBank from '../views/QuestionBank.vue'
import MessageBoard from '../views/MessageBoard.vue'

const routes = [
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true }
      },
      {
        path: '/study-plan',
        name: 'StudyPlan',
        component: StudyPlan,
        meta: { requiresAuth: true }
      },
      {
        path: '/subject',
        name: 'Subject',
        component: Subject,
        meta: { requiresAuth: true }
      },
      {
        path: '/study-record',
        name: 'StudyRecord',
        component: StudyRecord,
        meta: { requiresAuth: true }
      },
      {
        path: '/question-bank',
        name: 'QuestionBank',
        component: QuestionBank,
        meta: { requiresAuth: true }
      },
      {
        path: '/message-board',
        name: 'MessageBoard',
        component: MessageBoard,
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  // 捕获所有未匹配的路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user')
  
  // 如果路由需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查是否已登录
    if (!isAuthenticated) {
      // 如果没有登录，重定向到登录页面
      next('/login')
    } else {
      next()
    }
  } else {
    // 如果路由不需要认证
    // 但用户已登录且试图访问登录页
    if (to.path === '/login' && isAuthenticated) {
      next('/')
    } else {
      next()
    }
  }
})

export default router 